package cn.xy.base.server.controller.admapi;

import cn.xy.base.server.dto.AdminLoginDTO;
import cn.xy.base.server.po.SysAdmin;
import cn.xy.base.server.po.SysPermission;
import cn.xy.base.server.po.SysRole;
import cn.xy.base.server.service.SysAdminService;
import cn.xy.base.server.service.SysPermissionService;
import cn.xy.base.server.service.SysRoleService;
import cn.xy.base.server.vo.LoginResult;
import cn.xy.base.server.vo.SysAdminVO;
import cn.xy.base.server.vo.SysRoleVO;
import cn.xy.base.server.web.AdminWebContext;
import cn.xy.commons.annotation.ApiAuth;
import cn.xy.commons.annotation.OperateLog;
import cn.xy.commons.constant.Consts;
import cn.xy.commons.core.Result;
import cn.xy.commons.enums.DisableStatus;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 主页接口
 *
 * @author auto
 */
@Slf4j
@RestController
@RequestMapping(value = "/admapi/sys")
@ApiAuth(ignore = true)
@Api(tags = {"主页接口"})
@ApiSort(0)
public class IndexAdminController {

    @Autowired
    private SysAdminService sysAdminService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @ApiOperation(value = "管理员登录", notes = "登陆成功则携带token返回")
    @PostMapping("/login")
    @OperateLog(description = "登录系统", ignoreData = true)
    public Result<LoginResult<SysAdminVO>> login(@RequestBody @Validated AdminLoginDTO loginDTO) {
        SysAdmin sysAdmin = sysAdminService.getByUsername(loginDTO.getUsername());
        if (sysAdmin == null) {
            return Result.error("账号或密码错误！");
        }
        if (!sysAdmin.getPassword().equals(sysAdminService.encodePassword(loginDTO.getPassword(), sysAdmin.getSalt()))) {
            return Result.error("账号或密码错误！");
        }
        if (DisableStatus.isDisable(sysAdmin.getStatus())) {
            return Result.error("用户已被禁止登录");
        }
        // 管理员的角色
        SysRole role = sysRoleService.getById(sysAdmin.getRoleId());
        if (role == null) {
            return Result.error("您的角色异常，无法登录系统");
        }
        // 角色的权限
        SysRoleVO roleVO = new SysRoleVO(role);
        List<Long> permissionIdList = Arrays.stream(role.getPermissions().split(Consts.COMMA)).map(Long::parseLong).collect(Collectors.toList());
        List<SysPermission> permissionList = sysPermissionService.getPermissionListByIdIn(permissionIdList);
        //生成jwt
        String token = sysAdminService.createJwt(sysAdmin);
        sysAdminService.login(sysAdmin.getId(), token, AdminWebContext.getIp());
        // 登陆返回
        SysAdminVO sysAdminVO = new SysAdminVO(sysAdmin);
        sysAdminVO.setPermissionList(sysPermissionService.generateTree(permissionList));
        sysAdminVO.setRole(roleVO);

        LoginResult<SysAdminVO> adminLoginResult = new LoginResult<>();
        adminLoginResult.setToken(token);
        adminLoginResult.setInfo(sysAdminVO);
        return Result.data(adminLoginResult);
    }

    @ApiOperation(value = "管理员退出登录")
    @PostMapping("/logout")
    @OperateLog(description = "退出系统")
    @ApiAuth(ignore = false)
    public Result<String> logout() {
        String token = AdminWebContext.getToken();
        int adminId = AdminWebContext.getAdminId();
        sysAdminService.logout(adminId, token);
        return Result.ok();
    }

}
